#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
完整調試：頁頭/頁偏移/映射/掃描/查詢
在 OperatingSystem 目錄下運行：
    python test/debug_storage.py
"""
import os
import sys
import tempfile
import shutil
import struct

CUR_DIR = os.path.dirname(os.path.abspath(__file__))
OS_DIR = os.path.dirname(CUR_DIR)
sys.path.insert(0, OS_DIR)

from storage_engine import StorageEngine
from table_schema import Column, ColumnType


def print_page_header(engine: StorageEngine, page_id: int):
    page_data = engine.get_page(page_id)
    if len(page_data) < 8:
        print(f"   ❌ 頁 {page_id} 大小異常: {len(page_data)}")
        return
    record_count, free_space_offset = struct.unpack('II', page_data[:8])
    print(f"   📄 頁 {page_id} 頭部: 記錄數={record_count}, 空閒偏移={free_space_offset}")
    print(f"      前32字節: {page_data[:32].hex()}")


def main():
    print("🔍 調試存儲引擎：頁面與掃描")
    print("=" * 50)

    temp_dir = tempfile.mkdtemp()
    db_path = os.path.join(temp_dir, "dbg_db")

    engine = StorageEngine(
        db_path=db_path,
        cache_size=8,
        enable_locking=False
    )

    # 構建表
    columns = [
        Column("id", ColumnType.INT, primary_key=True),
        Column("name", ColumnType.VARCHAR, length=50),
        Column("age", ColumnType.INT),
    ]

    print("1️⃣ 建表...")
    ok = engine.create_table("people", columns)
    print(f"   結果: {'✅' if ok else '❌'}")

    print("2️⃣ 插入三條數據...")
    rows = [
        {"id": 1, "name": "Alice", "age": 25},
        {"id": 2, "name": "Bob", "age": 30},
        {"id": 3, "name": "Charlie", "age": 35},
    ]
    for r in rows:
        ok = engine.insert_record("people", r)
        print(f"   插入 {r}: {'✅' if ok else '❌'}")

    print("3️⃣ 查看表頁面映射...")
    mapping = getattr(engine, 'table_pages', {}).get("people", [])
    print(f"   people -> 頁面: {mapping}")
    if not mapping:
        print("   ❌ 無頁面映射，建表/分頁可能失敗")

    print("4️⃣ 檢查各頁頭信息...")
    for pid in mapping:
        print_page_header(engine, pid)

    print("5️⃣ 全表掃描 select_records()...")
    found = engine.select_records("people")
    print(f"   select_records 返回 {len(found)} 條")
    for rec in found:
        print(f"   📝 {rec}")

    print("6️⃣ 直接掃描頁內容(_scan_page_records)...")
    schema = engine.table_schemas.get("people")
    if schema and mapping:
        total = 0
        for pid in sorted(set(mapping)):
            page_records = engine._scan_page_records(pid, schema)
            print(f"   頁 {pid} 掃描到 {len(page_records)} 條")
            for rr in page_records:
                print(f"     → {rr.to_dict()}")
            total += len(page_records)
        print(f"   合計掃描: {total} 條")
    else:
        print("   ❌ 缺少 schema 或頁面，無法直掃")

    print("7️⃣ 主鍵等值查詢測試...")
    pk2 = engine.select_records("people", {"id": 2})
    print(f"   按主鍵 id=2 查得: {pk2}")

    engine.close()
    shutil.rmtree(temp_dir)


if __name__ == "__main__":
    main()
